home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 1153 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.1 KB

  1. Path: sun001.spd.dsccc.com!sun001!dthornto
  2. From: dthornto@aplo266.spd.dsccc.com (Duane Thornton)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: HELP NEEDED: What the hell is wrong with my program?
  5. Date: 11 Jan 1996 18:57:03 GMT
  6. Organization: none
  7. Message-ID: <DTHORNTO.96Jan11125703@aplo266.spd.dsccc.com>
  8. References: <4d1qmp$h43@carbon.cudenver.edu>
  9. NNTP-Posting-Host: aplo266.spd.dsccc.com
  10. In-reply-to: exli@ouray.cudenver.edu's message of 11 Jan 1996 01:55:37 GMT
  11.  
  12. >>>>> On 11 Jan 1996 01:55:37 GMT, exli@ouray.cudenver.edu (ELLIE XIAO-YU LI) said:
  13.  
  14.     ELLIE> first of all, i have to thank all of you who have answered
  15.     ELLIE> me through email or have followed up my post.  and here is
  16.     ELLIE> more details about my problem.
  17.  
  18.     ELLIE> the system i am using is a dec osf/1.  the code is
  19.     ELLIE> something like:
  20.  
  21.     ELLIE> #include <string.h>
  22.  
  23.     ELLIE> typedef struct {
  24.     ELLIE>     .
  25.     ELLIE>     .
  26.     ELLIE>     .
  27.     ELLIE>     char *name;
  28.     ELLIE>     .
  29.     ELLIE>     .
  30.     ELLIE>     .
  31.     ELLIE> } aStruct;
  32.  
  33.     ELLIE> aStruct *ptr;
  34.     ELLIE> char *str1="this is a test";
  35.     ELLIE> char *str2="this is another test";
  36.  
  37.     ELLIE> ptr=(aStruct *)malloc(sizeof(aStruct));
  38.     ptr-> name=(char *)malloc(strlen(str1));
  39.  
  40.                                      ^^^^^This should be strlen(str1 + 1)
  41. The length returned by 'strlen' does not include the terminator
  42. (\0). Therefore the following 'strcpy' actually copies the terminator
  43. outside of the memory reserved by the above 'malloc'.
  44.  
  45.     ELLIE> strcpy(ptr->name, str1);            /*no problem here*/
  46.     ELLIE> ...
  47.     ELLIE> /*then later i want  ptr->name to point to another string*/
  48.     ELLIE> free(ptr->name);
  49.     ptr-> name=(char *)malloc(strlen(str2));
  50.     ELLIE> strcpy(ptr->name, str2);            /*problem arised here*/
  51.  
  52.  
  53.     [snip]
  54.  
  55.     ELLIE> Mitch
  56.     ELLIE> exli@ouray.cudenver.edu
  57.  
  58. Duane
  59. --
  60. Duane Thornton x94916 
  61.  
  62. ---------------------------- Duane Thornton --------------------------------
  63. Internet:  dthornto@spd.dsccc.com                       Opinions are my own.
  64. DSC Communications Corporation   Addr: MS 153, 1000 Coit Rd, Plano, TX 75075
  65. ----------------------------------------------------------------------------
  66.